<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
        .box {
            width: 200px;
            height: 100px;
            background-color: aqua;
            position: absolute;
            left: 50%;
            transform: translate(-50%);
            top: 100px;
        }
        
        .max {
            width: 100px;
            height: 2000px;
            background-color: cadetblue;
        }
    </style>
</head>

<body>
    <div class="box"></div>
    <div class="max"></div>
    <button>返回顶部</button>
    <script>
        // 获取元素
        var obox = document.getElementsByClassName("box")[0];
        var but = document.getElementsByTagName("button")[0];

        window.onscroll = function() {
            var top = document.documentElement.scrollTop || document.body.scrollTop;
            console.log(top);
            if (top > 100) {
                obox.style.position = "fixed";
                obox.style.top = 0;
            } else {
                obox.style.position = "absolute";
                obox.style.top = "100px";
            }
        };
        but.onclick = function() {
            var top = document.documentElement.scrollTop;

            function setTop() {
                setTimeout(function() {
                    top -= 100;
                    document.documentElement.scrollTop = top;
                    if (top > 0) {
                        setTop();
                    }
                }, 5);
            }
            setTop();
        };
    </script>
</body>

</html>